<script setup lang="ts">
import { formatDateTime } from '/@lib/utils/tool.ts'
import { ModalUtil } from '/@lib/utils/modal.ts'
import { useModalStatus } from '/@lib/hooks/useModalStatus.ts'
import { usePagination } from '/@lib/hooks/usePagination.ts'
import { useLoading } from '/@lib/hooks/useLoading.ts'
import { UserVO } from '/@/api/system/sysUser/types'
import { RoleVO } from '/@/api/system/sysRole/types'
import { ApiSysUser } from '/@/api/system/sysUser'

const { loading, showLoading, hideLoading } = useLoading()
const { modalVisible, modalTitle, showModal, hideModal, setModalTitle } = useModalStatus()
const {
  pageNum, pageSize, total, setTotal, onChangeCurrent, onChangePageSize
} = usePagination(() => getTableList())
const closeCancel = () => {
  hideModal()
}
const tableRef = ref()
const tableData = ref([])
const checkedKeys = ref<any[]>([])
const userInfo = ref<any>({})

/** 打开 Modal 操作 */
const open = async (row: UserVO) => {
  showModal()
  setModalTitle('分配角色')
  await handleOpenDefaultData(row)
}
defineExpose({ open })
const emit = defineEmits(['submit-success'])
/** 提交按钮 */
const submitForm = async () => {
  const userId = userInfo.value.userId
  const roleIds = checkedKeys.value.join(',')
  if (roleIds.length === 0) return ModalUtil.msgError('请选择角色')
  showLoading()
  try {
    await ApiSysUser.authRole({ userId: userId as string, roleIds })
    ModalUtil.msgSuccess('操作成功')
    hideModal()
  } finally {
    hideLoading()
  }
}
/** Modal Open 处理默认数据 */
const handleOpenDefaultData = async (row: UserVO) => {
  Object.assign(userInfo.value, row)
  await getTableList()
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: RoleVO[]) => {
  // userInfo.value.roleIds = selection.map((item) => item.roleId)
  checkedKeys.value = selection.map((item) => item.roleId)
}

const getTableList = async () => {
  showLoading()
  try {
    const res = await ApiSysUser.getAuthRole(userInfo.value.userId)
    tableData.value = res.list.slice((pageNum.value - 1) * pageSize.value, pageNum.value * pageSize.value)
    setTotal(res.list.length)
    checkedKeys.value = res.checkedKeys
    await nextTick(() => {
      checkedKeys.value.forEach((item: any) => {
        tableData.value.forEach((row: any) => {
          if (row.roleId === item) {
            tableRef.value.toggleRowSelection(row, true)
          }
        })
      })
    })
  } finally {
    hideLoading()
  }

}
</script>

<template>
  <el-dialog
    class="authRole-dialog"
    :title="modalTitle"
    v-model="modalVisible"
    width="50%"
    top="5vh"
    append-to-body
    destroy-on-close
    :close-on-click-modal="false"
  >
    <div class="flex-column flex-auto">
      <div class="flex-column width-full margin-bottom">
        <el-descriptions border :column="2">
          <template #title>
            <span class="text-primary">基本信息</span>
          </template>
          <el-descriptions-item label="用户昵称">{{ userInfo.nickName }}</el-descriptions-item>
          <el-descriptions-item label="登录账号">{{ userInfo.userName }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="flex-auto">
        <el-table
          ref="tableRef"
          v-loading="loading"
          :data="tableData"
          @selection-change="handleSelectionChange"
          border
          style="height: 100%"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column type="index" label="序号" width="55" align="center" />

          <!--  主内容   -->
          <el-table-column label="角色编号" align="center" prop="roleId" />
          <el-table-column label="角色名称" align="center" prop="roleName" />
          <el-table-column label="权限字符" align="center" prop="roleKey" />
          <el-table-column label="创建时间" align="center" prop="createTime" width="160">
            <template #default="scope">
              <span>{{ formatDateTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>

          <template #empty>
            <el-empty class="vip-data-empty" description="暂无数据" />
          </template>
        </el-table>
      </div>

      <VipPagination
        :current-page="pageNum"
        :page-size="pageSize"
        :total="total"
        layout="'prev, pager, next'"
        @current-change="onChangeCurrent"
        @size-change="onChangePageSize"
      />
    </div>

    <!-- 底部按钮 -->
    <template #footer>
      <div>
        <el-button @click="closeCancel">取消</el-button>
        <el-button :loading="loading" type="primary" @click="submitForm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss">
.authRole-dialog {
  //height: 88vh !important;
  height: 550px !important;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .el-dialog__body {
    width: 100%;
    //height: 80%;
    flex: 1;
    display: flex;
    flex-flow: column;
    overflow: hidden;
  }
}
</style>

<style lang="scss" scoped>
:deep(.el-descriptions__label) {
  width: 120px;
}
</style>
